using Server.Modeels;
using System;
using DBLibrary.HLBJMemoryTool;
using System.Linq;
using Microsoft.Extensions.Logging;
using DevExpress.Xpo;
using System.Threading.Tasks;

namespace Server.Services
{
    public class AuthService : IAuthService
    {
        private readonly HLBJMemoryToolUnitOfWork _unitOfWork;
        private readonly ILogger<AuthService> _logger;

        public AuthService(HLBJMemoryToolUnitOfWork unitOfWork, ILogger<AuthService> logger)
        {
            _unitOfWork = unitOfWork;
            _logger = logger;
        }

        // 实际的身份验证服务，使用UserInfo表进行验证
        public Task<LoginResponse> LoginAsync(LoginRequest request)
        {
            try
            {
                // 参数验证
                if (request == null)
                {
                    return Task.FromResult(new LoginResponse
                    {
                        Success = false,
                        Message = "请求参数为空",
                        Token = null,
                        User = null
                    });
                }

                // 从数据库中查找用户
                _logger.LogInformation("尝试验证用户: {Username}", request.Username);
                var user = new XPQuery<DBLibrary.HLBJMemoryTool.UserInfo>(_unitOfWork)
                    .FirstOrDefault(u => u.UserName == request.Username && u.PassWord == request.Password);

                if (user != null)
                {
                    _logger.LogInformation("用户验证成功: {Username}", request.Username);
                    return Task.FromResult(new LoginResponse
                    {
                        Success = true,
                        Message = "登录成功",
                        Token = GenerateMockToken(user.UserName),
                        User = new UserDto
                        {
                            Id = user.Id, // 添加用户ID
                            Username = user.UserName,
                            Email = $"{user.UserName}@example.com", // 假设Email字段未在数据库中存储
                            Role = "User",
                            IsAuthenticated = true
                        }
                    });
                }
                else
                {
                    _logger.LogWarning("用户验证失败: {Username}", request.Username);
                    return Task.FromResult(new LoginResponse
                    {
                        Success = false,
                        Message = "用户名或密码错误",
                        Token = null,
                        User = null
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "验证用户时发生错误");
                return Task.FromResult(new LoginResponse
                {
                    Success = false,
                    Message = "服务器内部错误",
                    Token = null,
                    User = null
                });
            }
        }

        // 生成模拟的身份验证令牌
        private string GenerateMockToken(string username)
        {
            // 在实际项目中，应该使用JWT或其他安全的令牌生成方式
            return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{username}:{DateTime.UtcNow.Ticks}"));
        }
    }
}
